import { Kline } from "../entitys/Kline";
import { AppDataSource } from "../type-orm";

const klineRepository = AppDataSource.getRepository(Kline);

export const getKlinesByCode = async (code: string) => {
  return await klineRepository.find({
    where: { code },
  });
};


export const getKline = async (code: string,date:string) => {
  return await klineRepository.find({
    where: { code,date},
  });
};


export const saveKlines = async (kline: Kline[]) => {
    return await klineRepository.save(kline);
};

export const saveKline=async (kline: Kline) => {
  // const klines=await getKlinesByCode(kline?.code);
  // if(!klines?.length){
  //   return Promise.reject(`没有此股票${kline?.code}!`);
  // }
  const existedKLines=await getKline(kline?.code,kline?.date);
  if(existedKLines?.length){
    return Promise.resolve(`此股票${kline?.code}已存在K线数据${kline?.date}!`);
  }
  return await klineRepository.save(kline);
};

export const getKlineCodes = async () => {
   return await klineRepository.createQueryBuilder("kline")
        .select("DISTINCT kline.code", "code")
        .getRawMany();
};

export const getKlineCodesByDate = async (date: string) => {
  return await klineRepository.createQueryBuilder("kline")
    .select("DISTINCT kline.code", "code")
    .where("kline.date = :date", { date })
    .getRawMany();
};